//
//  UpdateHeaderViewController.m
//  myhuibao
//
//  Created by 孙昕 on 14-2-12.
//  Copyright (c) 2014年 myhuibao. All rights reserved.
//

#import "UpdateHeaderViewController.h"
#import<QuartzCore/QuartzCore.h>
#import "OMGToast.h"
#import "Config.h"
#import "SBJson.h"
@interface UpdateHeaderViewController ()

@end

@implementation UpdateHeaderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _lbName.delegate=self;
    _lbPrice.delegate=self;
    _ScrollView.delegate=self;
    bSelect=NO;
    arrayDishName=[[NSMutableArray alloc] initWithCapacity:30];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:_lbName];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)OnBack:(id)sender {
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_lbName];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)OnCancel:(id)sender {
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_lbName];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)OnUpdate:(id)sender {
    if(_lbName.text==nil|| [_lbName.text isEqualToString:@""] || [[_lbName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""])
    {
          [OMGToast showWithText:@"菜品名称不能为空" bottomOffset:100];
        return;
    }else if([_lbName.text length]>10)
    {
        [OMGToast showWithText:@"菜品名称不能超过10个字" bottomOffset:100];
        return;
    }
    else if(!bSelect)
    {
        [OMGToast showWithText:@"请选择图片" bottomOffset:100];
        return;
    }
    if(_lbPrice.text==nil || [_lbPrice.text isEqualToString:@""] || [[_lbPrice.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""])
    {
        _lbPrice.text=@"";
    }
    else
    {
        if([_lbPrice.text intValue]<=0)
        {
            [OMGToast showWithText:@"菜品价格必须为正整数" bottomOffset:100];
            return;
        }else if ([_lbPrice.text length]>5)
        {
            [OMGToast showWithText:@"菜品价格必须在5位之内" bottomOffset:100];
            return;
        }else if ([_lbPrice.text floatValue]!=[_lbPrice.text intValue] || [_lbPrice.text rangeOfString:@"." options:NSCaseInsensitiveSearch].length>0)
        {
            [OMGToast showWithText:@"菜品价格不能为小数" bottomOffset:100];
            return;
        }
    }
    for(NSString *name in arrayDishName)
    {
        if([name isEqualToString:_lbName.text])
        {
            [OMGToast showWithText:@"你已经上传该菜品" bottomOffset:100];
            return;
        }
    }
    UIGraphicsBeginImageContextWithOptions(_ScrollView.bounds.size, YES, 0);
    
    //this is the key
    CGPoint offset=_ScrollView.contentOffset;
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y);
    
    [_ScrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:@"updatetemp.jpg"]];
    [UIImageJPEGRepresentation(visibleScrollViewImage, 0.5) writeToFile:imageDataPath atomically:YES];
    NSURL *url = [NSURL  URLWithString:url_uploadproduct];
    req = [ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getMemberId]] forKey:@"member.memberID"];
    [req setPostValue:[[Config Instance] getPassword] forKey:@"member.password"];
    [req setFile:imageDataPath forKey:@"image"];
    [req setPostValue:@"updatetemp.png" forKey:@"imageFileName"];
    [req setPostValue:[NSString stringWithFormat:@"%d",_merchantID] forKey:@"merchantID"];
    [req setPostValue:[_lbName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]  forKey:@"productName"];
    [req setPostValue:_lbPrice.text forKey:@"productPrice"];
    [req setPostValue:@"" forKey:@"memo"];
    [req buildRequestHeaders];
    [req setDidFinishSelector:@selector(UpdateFinish:)];
    req.delegate=self;
    [req startAsynchronous];
}

-(void)UpdateFinish:(ASIHTTPRequest*)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    [OMGToast showWithText:[dic objectForKey:@"log"] bottomOffset:100];
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        [arrayDishName addObject:_lbName.text];
    }
}

- (IBAction)OnGetPhoto:(id)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择相片来源"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"照相机", @"相册", nil];
    [sheet showInView:self.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType;
    if(buttonIndex==0)
    {
        sourceType=UIImagePickerControllerSourceTypeCamera;
    }else if(buttonIndex==1)
    {
        sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    }else
    {
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    [self presentModalViewController:picker animated:YES];//进入照相界面
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _ImageView;  //返回要滚动的subview，通常只有一个subview要滚动的。
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _ImageView.frame=CGRectMake(0, 0, 280, image.size.height*280/image.size.width);
    
    _ImageView.image=image;
    _ScrollView.contentOffset=CGPointMake(0, 0);
    _ScrollView.contentSize = CGSizeMake(_ImageView.frame.size.width, _ImageView.frame.size.height);
    bSelect=YES;
    [self dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    [theTextField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField:textField up:NO];
}

-(void)animateTextField:(UITextField *)textField up:(BOOL)up
{
    const int movementDistance = 180;
    const float movementDuration = 0.3f;
    int movement = (up?-movementDistance:movementDistance);
    [UIView beginAnimations:@"anim" context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
   // if(textField==_lbName)
    //{
    //    NSInteger strLength = textField.text.length - range.length + string.length;
    //    return (strLength <= 10);
  //  }
     if(textField==_lbPrice)
    {
        NSInteger strLength = textField.text.length - range.length + string.length;
        return (strLength <= 5);
    }
    return YES;
}

-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 10) {
                textField.text = [toBeString substringToIndex:10];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > 10 ) {
            textField.text = [toBeString substringToIndex:10];
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([_lbName isFirstResponder] || [_lbPrice isFirstResponder])
    {
        [_lbName resignFirstResponder];
        [_lbPrice resignFirstResponder];
        //[self animateTextField:nil up:NO];
    }

}
@end
